require(["common", "jQuery", "coAjax", "queryString", "hash_routie"], function(jSouper, $, coAjax, QueryString, hash_routie) {
	/*
	 * 获取导购链接列表
	 */
	var _num = 10;
	hash_routie.on("shoppinguide", function() {
		var _page = 0;
		App.set('title', '导购链接')
		_load_guide_list(_num, _page);
		_load_guide_config();
	});

	function _load_guide_list() {
		coAjax.get(appConfig.bus.guide_list, function(result) {
			App.set("$Cache.bus.guide_list", result.result);
		});
	};
	/*
	 * 获取配置
	 */
	function _load_guide_config(argument) {
		coAjax.get(appConfig.bus.guide_config, function(result) {
			App.set("$Cache.bus.guide_config", result.result)
		});
	};
	/*
	 * 修改配置
	 */
	function _upload_guide_config() {
		var guide_config = App.get("$Cache.bus.guide_config");
		guide_config = guide_config.sort(function(a, b) {
			return a.max_price > b.max_price
		});
		coAjax.put(appConfig.bus.update_guide_config, {
			guide_config: guide_config
		}, function(result) {
			alert("success", "导购链接规则修改成功")
			App.set("$Cache.bus.guide_config", result.result);
		});
	};



	/*
	 * 导购链接的增删改
	 */
	App.set("$Event.bus.add_guide", function(e, vm) {
		coAjax.post(appConfig.bus.guide_add, {
			user_phone: App.get("$Cache.new_guide.phone_number")
		}, function(result) {
			App.set('$Cache.new_guide.phone_number', '');
			App.set("$Cache.bus.guide_list", result.result);
		});
	});
	App.set("$Event.bus.remove_guide", function(e, vm) {
		coAjax["delete"](appConfig.bus.guide_remove, {
			guide_id: vm.get("_id")
		}, function(result) {
			App.set("$Cache.bus.guide_list", result.result);
		});
	});
	App.set("$Event.bus.build_guide_url", function(e, vm) {
		coAjax.get(appConfig.bus.guide_url, {
			guide_id: vm.get("_id")
		}, function(result) {
			// vm.set()
			vm.set("guide_link", result.result);
		});
	});
	/*
	 * 导购配置的增删改
	 */
	App.set("$Top.$Event.guide_config.add", function() {
		var guide_config = App.get("$Cache.bus.guide_config");
		var new_guide_config = App.get("$Cache.new_guide_config");
		guide_config.push({
			max_price: +new_guide_config.max_price,
			rate: +new_guide_config.rate
		});
		//清空
		App.set("$Cache.new_guide_config", {});
		_upload_guide_config();
	});
	App.set("$Event.guide_config.update", function(e, vm) {
		var is_updatting = vm.get("$Private.is_updatting");
		if (is_updatting) {
			vm.set("$Private.is_updatting", false);
			_upload_guide_config();
		} else {
			vm.set("$Private.is_updatting", true);
		}
		console.log(is_updatting, vm.get("$Private.is_updatting"));
	});
	App.set("$Top.$Event.guide_config.remove", function(e, vm) {
		vm.remove();
		_upload_guide_config();
	});
	/*
	 * 现金兑换功能的状态修改
	 */
	App.set("$Event.bus.guide.shenqingduihuanzhong_to_shangjiayijingfukuan", function(e, vm) {
		coAjax.put(appConfig.bus.guide_shenqingduihuanzhong_to_shangjiayijingfukuan, {
			user_id: vm.get("user_id")
		}, function(result) {
			vm.set(result.result);
		});
	});
});